﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using BusinessLogic.Interfaces;
using Domain;
using Domain.Entities;

namespace BusinessLogic.Implementations
{
    public class EFOrderDetailRepository : IOrderDetailRepository
    {
        private EFDbContext context;

        public EFOrderDetailRepository(EFDbContext context)
        {
            this.context = context;
        }

        public IEnumerable<OrderDetail> GetOrderDetails()
        {
            return context.OrderDetails.ToList();
        }

        public OrderDetail GetOrderDetailById(int id)
        {
            return context.OrderDetails.FirstOrDefault(i => i.Id == id);
        }

        public void DeleteOrderDetailById(int id)
        {
            context.OrderDetails.Remove(GetOrderDetailById(id));
            context.SaveChanges();
        }

        public void CreateOrderDetail(OrderDetail orderDetail)
        {
            context.OrderDetails.Add(orderDetail);
            context.SaveChanges();
        }

        public void SaveOrderDetail(OrderDetail orderDetail)
        {
            if (orderDetail.Id == 0)
            {
                CreateOrderDetail(orderDetail);
            }
            else
            {
                context.Entry(orderDetail).State = EntityState.Modified;
            }
            context.SaveChanges();
        }
    }
}
